package com.ly.mpayment.rest.up.maiyuanhf;

import com.ly.mpayment.core.secuity.MD5;
import com.ly.mpayment.core.util.*;
import com.ly.mpayment.persist.entity.UpOrder;
import com.ly.mpayment.persist.entity.UpShopInfo;
import com.ly.mpayment.persist.service.downrechargeflow.IDownRechargeFlowService;
import com.ly.mpayment.persist.service.downshopinfo.IDownShopInfoService;
import com.ly.mpayment.persist.service.uporder.IUporderService;
import com.ly.mpayment.rest.recharge.RechargeRest;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestBody;

import javax.ws.rs.POST;
import javax.ws.rs.Path;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

@Component
@Path("maiyuanhf")
public class MaiYuanhfRest {
	static Logger logger = Logger.getLogger(MaiYuanhfRest.class);

	public static final String version = "h1.1";

	public static final String defaultStr = "v="+version+"&action=";

	public static final String codeSuccess = "0";

	public static final int range [] = {0,1};

	public static final int resultStatus [] = {4,3,5,7,2};

	@Autowired
	IUporderService upOrderService;

	@Autowired
	private ThreadPoolTaskExecutor taskExecutor;

	@Autowired
	IDownRechargeFlowService flowService;

	@Autowired
	IDownShopInfoService shopService;
//	返回错误定义
//	0	成功
//	001	参数错误
//	002	充值号码不合法
//	003	帐号密码错误
//	004	余额不足
//	005	不存在指定流量包
//	006	不支持该地区
//	007	卡号或者密码错误
//	008	该卡已使用过
//	009	该卡不支持(移动/电信/联通)号码
//	010	协议版本错误
//	999	其他错误


	/**
	 * TaskID	任务编码	失败为0
		Code	代码	成功为0
		Message		消息	注意：启用商户订单号唯一性验证后，如果手机号码+商户订单号存在，Code会返回0，表示成功。Message提示为：商户订单号xxx已经存在
		但不会再新建订单，TaskID将会返回上一次相同商户订单号提交返回的TaskID。如果TaskID返回为-1，需要人工介入判断。

	 * 单号码充值
	 * @param phoneNum
	 * @param upOrderUuid
	 * @param packageNo
	 * @return
	 */
	@SuppressWarnings("static-access")
	public String charge(String phoneNum,String upOrderUuid,String packageNo,String account,String apikey
			,String backurl,String commitUrl,String range){
		Map<String, Object> paras = MapUtil.getMap();
		paras.put("account", account);
		paras.put("Mobile",phoneNum);
		paras.put("BackUrl",backurl);
		paras.put("Package",packageNo);
		paras.put("Range",range);
		paras.put("OutTradeNo", upOrderUuid);
		com.alibaba.fastjson.JSONObject object = new com.alibaba.fastjson.JSONObject();
		object.put("account",account);
		object.put("mobile",phoneNum);
		object.put("package",packageNo);
		String url = defaultStr+"charge&Account="+account+"&Mobile="+phoneNum+"&Range="+range+
				"&OutTradeNo="+upOrderUuid+"&Package="+packageNo+"&Sign="+MD5.md5(StringSort.doSign(object)+"&key="+apikey);
		logger.info("maiyuan_charge:"+url+":"+StringSort.doSign(object)+"&key="+apikey);
		String result = HttpClient.httpGetUrl(commitUrl.concat("?")+url);
		logger.info("maiyuan_charge_result:"+result);
		if(!StringUtils.isBlank(result)){
			return result;
		}
		return null;
	}

	/**
	 *     TaskID	任务
		    Mobile	手机
		    Status	状态	2.充值中(该状态时号码可能为空)
						3.提交失败
						4.充值成功
						5.充值失败
						7.未知(待处理)
		    ReportTime	时间
		    ReportCode	代码说明
		    OutTradeNo	商户订单号	商户系统内部的订单号

	 * @param upOrderUuid
	 * @param sendTime
	 * @return
	 */
	public  String queryReport(String upOrderUuid,String sendTime,String account,String apikey,String queryUrl){
		Map<String, Object> paras = MapUtil.getMap();
		paras.put("account", account);
		com.alibaba.fastjson.JSONObject object = new com.alibaba.fastjson.JSONObject();
		object.put("account",account);
		String url = defaultStr+"queryReport&account="+account+"&OutTradeNo="+upOrderUuid+"&SendTime="+sendTime+"&sign="+MD5.md5(StringSort.doSign(object)+"&key="+apikey);
		String result = HttpClient.httpGetUrl(queryUrl.concat("?")+url);
		if(!StringUtils.isBlank(result)){
			JSONObject json = JSONObject.fromObject(result);
			if(json.getString("Code").equals(codeSuccess)){
				return json.getString("Reports").toString();
			}
		}
		return null;
	}


	/**
	 * 增加签名
	 * [{"TaskID":3,"Mobile":"13789679619","Status":5,"ReportTime":"2015-06-24T15:52:54.73","ReportCode":"S:终止",“Sign”:” 6a917a805ea17ac05bf231d242dc3c37”},{"TaskID":4,"Mobile":"13789679618","Status":4,"ReportTime":"2015-06-24T16:32:35.583","ReportCode":"成功", “Sign”:” 6a917a805ea17ac05bf231d242dc3c37”}]
	 * @param data
	 * @return
	 */
	@SuppressWarnings("-access")
	@POST
	@Path("callBack")
	public synchronized String callBack(@RequestBody String data){
		logger.info("maiyuan_callBack:"+data);
		if(!StringUtils.isBlank(data)){
			try {
				JSONArray array = JSONArray.fromObject(data);
				for(int i = 0 ; i < array.size(); i++){
					if(array.getJSONObject(i).containsKey("TaskID") && array.getJSONObject(i).containsKey("OutTradeNo")){
						//{"TaskID":103724743,"Mobile":"13922896815","Status":4,"ReportTime":"2023-01-18T22:31:06.997","ReportCode":"2:",
						// "OutTradeNo":"2c922ab9855433230185c54422d97e34","ReceiptNum":"",
						// "Sign":"1040b61cd1967948ad7955e4a5a1a8fd","ChargeType":2,"Price":10.2600}
						UpOrder order = upOrderService.findById(array.getJSONObject(i).getString("OutTradeNo").trim());
						if(array.getJSONObject(i).getInt("Status") == 4 && order != null && order.getStatus() == Config.status[0]){
							order.setRemark(StringUtils.isBlank(array.getJSONObject(i).getString("ReceiptNum")) ? "" : array.getJSONObject(i).getString("ReceiptNum"));
							RechargeRest.successUpOrder.add(order);
						}else if(array.getJSONObject(i).getInt("Status") == 5 && order != null && order.getStatus() == Config.status[0]){
							order.setRemark(array.getJSONObject(i).getString("Status"));
							RechargeRest.failtUpOrder.add(order);
						}else{
							logger.info("maiyuan_not_found_order:"+data);
						}
					}
				}
				return "ok";
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return "falit";
	}

	public void commitOrder(UpOrder order, UpShopInfo shop) {
		try {
			UpOrder product = upOrderService.findOrderProduct(order.getUporderuuid());
			if (product != null) {
				String packages[] = product.getUpShopPro().getProductCode().split("\\|");
				String result = charge(order.getUpphonenum(), order.getUporderuuid(), packages[1],
						shop.getAppId(),shop.getUpkey(),shop.getOrderCallAddress(),shop.getOrderCommitAddress(),
						packages[0]);
				logger.info("commitmaiyuan_result:" + result);
				if (!StringUtils.isBlank(result)) {
					try{
						JSONObject json = JSONObject.fromObject(result);
						if(json.getString("Code").equals("0")){
							this.upOrderService.updateUpOrderMsg(order, json.getString("TaskID"),json.getString("Message"));
						}else if (result.contains("Code") && result.contains("Message")) {
							if (codesError.contains(json.getString("Code"))) {
								order.setRemark(json.getString("Code"));
								RechargeRest.failtUpOrder.add(order);
							} else {
								this.upOrderService.updateUpOrderMsg(order, "",json.getString("Code"));
							}
						}
					}catch (Exception e){
						e.printStackTrace();
						upOrderService.updateUpOrderArtificial(order, "","提单失败:");
					}
				} else {
					this.upOrderService.updateUpOrderArtificial(order, "", Config.commitFailt);
					logger.info("commitmaiyuan_error" + order.getUpphonenum());
				}
			}else{
				logger.info("commitmaiyuan error not found product" + order.getUporderuuid());
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.info(e.getMessage());
			this.upOrderService.updateUpOrderArtificial(order, "", Config.commitFailt);
			logger.info("commitmaiyuan_error+" + order.getUpphonenum());
		}
	}
	private static Set<String> codesError = new HashSet<String>(){{
		add("001");
		add("002");
		add("003");
		add("004");
		add("005");
		add("006");
		add("007");
		add("008");
		add("009");
		add("100");
		add("010");
	}};

	public void queryOrder(UpOrder upOrder, UpShopInfo shopInfo) {
		String result = queryReport(upOrder.getUporderuuid(), DateUtils.toShortDate(upOrder.getCreatetime()),shopInfo.getAppId(),
				shopInfo.getUpkey(),shopInfo.getOrderStatusAddress());
		logger.info("maiyuan_queryReport:"+result);
		if(result != null){
			JSONArray arrays = JSONArray.fromObject(result);
			for(int i = 0 ; i < arrays.size(); i++){
				JSONObject json = arrays.getJSONObject(i);
				UpOrder order = upOrderService.findById(json.getString("OutTradeNo").trim());
				if(json.getInt("Status") == 4 && order != null && order.getStatus() == Config.status[0]){
					order.setRemark(json.getString("Status"));
					RechargeRest.successUpOrder.add(order);
				}else if( (json.getInt("Status") == 5 || json.getInt("Status") == 3) && order != null && order.getStatus() == Config.status[0]){
					order.setRemark(json.getString("Status"));
					RechargeRest.failtUpOrder.add(order);
				}
			}
		}else{
			logger.info("maiyuan order failt:"+upOrder.getUpphonenum());
		}
	}

}
